package com.chat.common.common.event.Listener;

import com.chat.common.chat.dao.MessageDao;
import com.chat.common.chat.domain.entity.Message;
import com.chat.common.chat.domain.entity.Room;
import com.chat.common.chat.domain.enums.HotFlagEnum;
import com.chat.common.chat.service.cache.RoomCaChe;
import com.chat.common.common.constant.MQConstant;
import com.chat.common.common.domain.dto.MsgSendMessageDTO;
import com.chat.common.common.event.MessageSendEvent;
import com.chat.transaction.service.MQProducer;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;
import java.util.Objects;

@Slf4j
@Component
public class MessageSendListener {
    @Resource
    private MQProducer mqProducer;
    @Resource
    private MessageDao messageDao;
    @Resource
    private RoomCaChe roomCaChe;

    //事务前 发送mq 消息
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT,classes = MessageSendEvent.class,fallbackExecution = true)
    public void  messageRoute(MessageSendEvent event){
        Long msgId = event.getMsgId();
        mqProducer.sendSecureMsg(MQConstant.SEND_MSG_TOPIC, new MsgSendMessageDTO(msgId), msgId);
    }

    @TransactionalEventListener(classes = MessageSendEvent.class, fallbackExecution = true)
    public void handlerMsg(@NotNull MessageSendEvent event) {
        Message message = messageDao.getById(event.getMsgId());
        Room room = roomCaChe.get(message.getRoomId());
        if (isHotRoom(room)) {
            // todo 机器人
            //openAIService.chat(message);
        }
    }

    public boolean isHotRoom(Room room) {
        return Objects.equals(HotFlagEnum.YES.getType(), room.getHotFlag());
    }

}
